import http from '@/utils/request'
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage'
import store, { AppDispatch } from '..'
import { Channel, ChannelAction } from '../reducer/channel'

export const getChannels = () => async (dispatch: AppDispatch) => {
  if (hasToken()) {
    const res = await http.get('/v1_0/user/channels')
    console.log(1, res)
    dispatch({ type: 'channel/saveList', payload: res.data.channels })
  } else {
    const localList = getLocalChannels()

    if (localList.length) {
      dispatch({ type: 'channel/saveList', payload: localList })
    } else {
      const res = await http.get('/v1_0/user/channels')
      console.log(2, res)
      setLocalChannels(res.data.channels)
      dispatch({ type: 'channel/saveList', payload: res.data.channels })
    }
  }
}

export const getAllChannels = () => async (disoatch: AppDispatch) => {
  const res = await http.get('/v1_0/channels')
  console.log(res)
  disoatch({ type: 'channel/saveAllList', payload: res.data.channels })
}

export const addChannel = (item: Channel) => async (dispatch: AppDispatch) => {
  const { list } = store.getState().channel
  const channels = [...list, item]
  if (hasToken()) {
    const res = await http.patch('/v1_0/user/channels', { channels: channels })
    console.log(res)
  } else {
    setLocalChannels(channels)
  }
  dispatch({ type: 'channel/saveList', payload: channels })
}

/**
 * 删除指定用户频道
 * @param item
 * @returns
 */
export const deleteChannel = (id: number) => async (dispatch: AppDispatch) => {
  const { list } = store.getState().channel
  const newList = list.filter((item) => item.id !== id)
  if (hasToken()) {
    const res = http.delete('/v1_0/user/channels/' + id)
    console.log(res)
  } else {
    setLocalChannels(newList)
  }
  dispatch({ type: 'channel/saveList', payload: newList })
}

export const changeChannelId = (id: number): ChannelAction => ({
  type: 'channel/changeActiveId',
  payload: id,
})
